<?php
require_once '../model/conn.php';
require_once '../model/artinfo.php';

header('Content-Type: application/json');

$sql = "select * from tbl_user where uname ='$_POST[uname]'";
$uid = intval(exec_select($sql)[0]['uid']);

$aid = isset($_POST['aid']) ? intval($_POST['aid']) : 0;

if ($uid <= 0 || $aid <= 0) {
  echo json_encode(['code' => 400, 'msg' => '参数错误']);
  exit;
}

// 检查是否已点赞
if (isUserLike($uid, $aid) == 'yes') {
  $sql = "delete from tbl_article_like where uid=$uid and article_id=$aid";
  if (exec_update($sql)) {
    echo json_encode(['code' => 200, 'msg' => '取消点赞成功', 'liked' => false]);
  } else {
    echo json_encode(['code' => 500, 'msg' => '取消点赞失败']);
  }
  exit;
}

// 执行点赞
$sql = "insert into tbl_article_like values(null, $uid, $aid)";
if (exec_update($sql)) {
  echo json_encode(['code' => 200, 'msg' => '点赞成功', 'liked' => true]);
} else {
  echo json_encode(['code' => 500, 'msg' => '点赞失败']);
}
